<template>
  <div class="stock-data-view">
    <!-- 股票信息展示 -->
    <div v-if="stockInfo" class="stock-info-panel">
      <!-- 股票信息汇总模块 -->
      <div class="module-container">
        <StockInfoSummary :stock-info="stockInfo" />
      </div>

      <!-- K线图模块容器 -->
      <div class="module-container chart-container">
        <KLineChart
          :data="chartData"
          :title="`${stockInfo.name || stockInfo.code} K线图`"
          :loading="chartLoading"
          :show-volume="true"
          height="520px"
          @chart-click="handleChartClick"
        />
      </div>
      <!-- 预测面板模块 -->
      <div class="module-container prediction-container">
        <PredictionPanel :stock-code="stockInfo.code" @prediction-completed="handlePredictionCompleted" @prediction-error="handlePredictionError" />
      </div>
    </div>

    <!-- 无数据提示 -->
    <EmptyState v-if="!loading && !error && shouldShowNoData" :description="getEmptyDescription()" :show-retry="searchAttempted" @retry="handleRetry" />
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, watch } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRoute } from 'vue-router';
  import request from '../utils/request.js';
  import StockInfoSummary from '../components/StockInfoSummary.vue';
  import KLineChart from '../components/KLineChart.vue';
  import EmptyState from '../components/EmptyState.vue';
  import PredictionPanel from '../components/PredictionPanel.vue';
  import { useAppStatusStore } from '@/stores/appStatus';

  const route = useRoute();
  const appStore = useAppStatusStore();

  const stockInfo = ref(null);
  const loading = ref(false);
  const error = ref(null);
  const searchAttempted = ref(false);
  const retryCount = ref(0);
  const chartData = ref([]);
  const chartLoading = ref(false);
  const predictionData = ref(null);

  const shouldShowNoData = computed(() => {
    return !stockInfo.value;
  });

  const getEmptyDescription = () => {
    if (!searchAttempted.value) {
      return '请输入股票代码开始查询股票数据';
    }
    const stockCode = route.params.code;
    return stockCode ? `未找到股票代码 "${stockCode}" 的相关数据` : '未找到符合条件的股票数据';
  };

  // 获取K线数据
  const fetchChartData = async stockCode => {
    if (!stockCode) return;

    chartLoading.value = true;
    try {
      // 获取最近30天的数据
      const endDate = new Date().toISOString().split('T')[0];
      const startDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];

      const response = await request.post('/stock/data', {
        stock_code: stockCode,
        start_date: startDate,
        end_date: endDate,
      });

      chartData.value = response.data.data || [];
    } catch (error) {
      console.error('获取K线数据失败:', error);
      ElMessage.warning('K线数据加载失败，请稍后重试');
      chartData.value = [];
    } finally {
      chartLoading.value = false;
    }
  };

  // 处理图表点击事件
  const handleChartClick = params => {
    console.log('图表点击事件:', params);
  };

  // 处理预测完成事件
  const handlePredictionCompleted = data => {
    console.log('预测完成:', data);
    predictionData.value = data;
    ElMessage.success(`预测完成！生成了 ${data.predictions.length} 个预测点`);
  };

  // 处理预测错误事件
  const handlePredictionError = error => {
    console.error('预测错误:', error);
    predictionData.value = null;

    const errorMessage = error.response?.data?.detail || '预测失败，请稍后重试';
    ElMessage.error(errorMessage);
  };

  const handleSearch = async (stockCode = null) => {
    const codeToSearch = stockCode || route.params.code;

    if (!codeToSearch) {
      ElMessage.warning('请输入股票代码');
      return;
    }

    loading.value = true;
    error.value = null;
    searchAttempted.value = true;

    // 清除之前的预测数据
    predictionData.value = null;

    // 更新应用加载状态
    appStore.setLoading(true);

    try {
      // 获取股票基本信息
      const infoResponse = await request.post('/stock/info', {
        stock_code: codeToSearch,
      });
      // 后端返回的数据结构是 { data: {...}, field_descriptions: {...} }
      stockInfo.value = infoResponse.data.data;

      // 获取K线数据
      await fetchChartData(codeToSearch);
    } catch (err) {
      error.value = err;
      stockInfo.value = null;
      chartData.value = [];
      predictionData.value = null;

      ElMessage.error(err.message);
    } finally {
      loading.value = false;
      appStore.setLoading(false);
    }
  };

  const handleRetry = () => {
    retryCount.value++;
    error.value = null;
    handleSearch();
  };

  // 监听路由参数变化
  watch(
    () => route.params.code,
    newCode => {
      if (newCode) {
        handleSearch(newCode);
      }
    }
  );

  // 组件挂载时的逻辑
  onMounted(() => {
    // 如果路由中有股票代码，自动查询
    if (route.params.code) {
      handleSearch();
    }
  });
</script>

<style scoped>
  .stock-data-view {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
    min-height: calc(100vh - 70px);
  }

  /* 手机端股票数据视图优化 */
  @media (max-width: 768px) {
    .stock-data-view {
      max-width: 100%;
      padding: 0;
    }
  }

  .stock-info-panel {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 24px;
    padding: 0;
    margin-top: 20px;
  }

  /* 手机端股票信息面板优化 */
  @media (max-width: 768px) {
    .stock-info-panel {
      gap: 16px;
      margin-top: 12px;
    }
  }

  @media (max-width: 480px) {
    .stock-info-panel {
      gap: 12px;
      margin-top: 8px;
    }
  }

  .module-container {
    width: 100%;
    transition: all 0.3s ease;
  }

  .module-container:hover {
    transform: translateY(-2px);
  }

  .prediction-container {
    margin-top: 8px;
  }

  .chart-container {
    margin-top: 8px;
  }
</style>
